package com.smart.security.starter.config;

import com.smart.core.starter.config.FilterIgnorePropertiesConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.web.client.RestTemplate;


/**
 * 资源服务器配置
 *
 * @author guxiaobai
 * @date 2018/12/12 14:48
 */
public class BaseResourceServerConfigurer extends ResourceServerConfigurerAdapter {
    @Autowired
    private ResourceAuthExceptionEntryPoint resourceAuthExceptionEntryPoint;
    @Autowired
    private SmartAccessDeniedHandler smartAccessDeniedHandler;
    @Autowired
    private RemoteTokenServices remoteTokenServices;
    @Autowired
    private FilterIgnorePropertiesConfig filterIgnorePropertiesConfig;


    /**
     * 默认的配置，对外暴露
     *
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
        http.headers().frameOptions().disable();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>
                .ExpressionInterceptUrlRegistry registry = http
                .authorizeRequests();
        filterIgnorePropertiesConfig.getUrls()
                .forEach(url -> registry.antMatchers(url).permitAll());
        registry.anyRequest().authenticated()
                .and().csrf().disable();
    }

    /**
     * 提供子类重写
     * <p>
     * 1. 不重写，默认支持获取雍熙
     * 2. 重写notGetUser，提供性能
     * <p>
     * see codegen ResourceServerConfigurer
     *
     * @param resources
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        remoteTokenServices.setRestTemplate(lbRestTemplate());
        resources.authenticationEntryPoint(resourceAuthExceptionEntryPoint)
                .accessDeniedHandler(smartAccessDeniedHandler)
                .tokenServices(remoteTokenServices);
    }

    @Bean
    @LoadBalanced
    public RestTemplate lbRestTemplate() {
        return new RestTemplate();
    }


}
